/*
 * xor.c
 *
 *  Created on: 2014-11-10
 *      Author: HZY
 */


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "xor.h"

static void xOr(unsigned char* data, unsigned int dataLen, const char* passwd){
	unsigned int i;
	unsigned int pwdLen = strlen(passwd);
	for(i = 0; i < dataLen; i++){
		data[i] ^= passwd[i % pwdLen];
	}
}

void xOrFile(const char* path, const char* passwd, unsigned int maxLength){
	FILE* fp = NULL;
	long int fLen;
	unsigned char* buf = NULL;
	if(path == NULL || passwd == NULL){
		return;
	}
	fp = fopen(path, "rw+");
	if(fp == NULL){
		return;
	}
	if(fseek(fp, SEEK_END, 0) != 0){
		goto CLOSE;
	}
	fLen = ftell(fp);
	if(fseek(fp, SEEK_SET, 0) != 0){
		goto CLOSE;
	}
	if(fLen < maxLength){
		maxLength = fLen;
	}
	if((buf = malloc(maxLength)) == NULL){
		goto CLOSE;
	}
	if(fread(buf, 1, maxLength, fp) != maxLength){
		goto FREE;
	}
	if(fseek(fp, SEEK_SET, 0) != 0){
		goto FREE;
	}
	xOr(buf, maxLength, passwd);
	if(fwrite(buf, 1, maxLength, fp) != maxLength){
	}
FREE:
	free(buf);
CLOSE:
	fclose(fp);
	return;
}


